package main

import (
	"fmt"
	"github.com/jinzhu/gorm"
	"gogogo/gorm/model"
	"time"
)
import 	_ "github.com/go-sql-driver/mysql"


/*
   Author: mahaiyuan
   Date: 2021/2/24 8:02 下午
   Description:
*/
func main() {
	db, err := gorm.Open("mysql", "root:12345678@tcp(localhost:3306)/gogogo?charset=utf8mb4&parseTime=True&loc=Local")
	db.LogMode(true)	//开启日志 打印执行的sql
	db.SingularTable(true)
	if err != nil {
		panic("fail to connect db")
	}
	defer db.Close()

	t := &model.Teacher{JobNumber: "20210030001", Birthday: time.Now(), WorkAge: 1}
	db.Transaction(func(tx *gorm.DB) error {
		if err2 := tx.Create(t).Error; err2 != nil {
			fmt.Println("first insert error.", err2)
			// 返回错误事务回滚
			return err2
		}

		// 模拟重复插入
		if err2 := tx.Create(t).Error; err2 != nil {
			fmt.Println("second insert error.", err2)
			return err2
		}
		//返回nil提交事务
		return nil
	})

}
